package com.example.waimai.ui.home;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.example.waimai.HttpUtil.MyGet;
import com.example.waimai.HttpUtil.MyPost;
import com.example.waimai.MainActivity;
import com.example.waimai.context.UserInfoContext;
import com.example.waimai.eventInterface.FragmentEvent;
import com.example.waimai.pojo.Food;
import com.example.waimai.pojo.FoodType;
import com.example.waimai.pojo.Store;
import com.example.waimai.util.LocationUtil;
import com.example.waimai.util.MyThreadPool;
import com.example.waimaiandroid.R;
import com.example.waimaiandroid.diancanActivity;
import com.example.waimaiandroid.map.ZdpMapView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HomeFragment extends Fragment {

    //private HomeFragmentCallBack homeFragmentCallBack;

    /*public HomeFragment(HomeFragmentCallBack homeFragmentCallBack){
        this.homeFragmentCallBack = homeFragmentCallBack;
    }*/




    private static  LetterAdapter mLetterAdapter ;
    public static List<Store> stores = new ArrayList<>();
    // 设置一个事件的接口
    public FragmentEvent homeFragmentEvent;
    private boolean flag = true;
    public static View view ;
    public TextView UserCurrentAdd;
    private ImageView updateUserAddr ;

    public static Handler handler = new Handler(){
        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
                switch (msg.what){
                    case 1:
                        // 跳转Activity
                        Intent intent = new Intent();
                        intent.setComponent(new ComponentName(MainActivity.getMainActivity(), diancanActivity.class));
                        // 带数据
                        intent.putExtras(msg.getData());
                        MainActivity.getMainActivity().startActivity(intent);
                        //MainActivity.getMainActivity().finish();
                        break;
                    case 2:
                        // 更新数据
                        mLetterAdapter.updateAll(HomeFragment.stores);
                        break;
                    case 3:
                        // 店铺无菜品提醒
                        Toast.makeText(MainActivity.getMainActivity(),"该店铺暂无菜品",Toast.LENGTH_SHORT).show();
                        break;
                }
        }
    };

    // 菜单
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.refresh_menu,menu);
    }
    // 监听菜单


    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.refresh:
                // 找附近的店铺，然后显示
                if(UserInfoContext.currentLatLng == null){
                    // 先获取到定位
                    LocationUtil.startListener(MainActivity.getMainActivity());
                    Toast.makeText(MainActivity.getMainActivity(),"未获取到定位信息，请重试!",Toast.LENGTH_SHORT).show();
                    break;
                }
                String longitude = String.valueOf(UserInfoContext.currentLatLng.longitude);
                String latitude = String.valueOf(UserInfoContext.currentLatLng.latitude);
                MyThreadPool.doJob(new Runnable() {
                    @Override
                    public void run() {
                        Map<String,String> param = new HashMap<>();
                        param.put("longitude",longitude);
                        param.put("latitude",latitude);
                        stores = (List<Store>) MyPost.doPost("getMissedStore",param);
                        Message msg = new Message();
                        msg.what = 2;
                        handler.sendMessage(msg);
                    }
                });
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void getMissedStore(){

    }

    private LatLng userCurrent = null;

    private void initPosition(){
        LocationClient mLocationClient = new LocationClient(MainActivity.getMainActivity().getApplicationContext());
        LocationClientOption mOption = new LocationClientOption();
        mOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        mOption.setCoorType("bd09ll");
        mOption.setScanSpan(0);
        mOption.setOpenGps(true);
        mOption.setLocationNotify(false);
        mOption.setIgnoreKillProcess(false);
        mOption.SetIgnoreCacheException(false);
        mOption.setWifiCacheTimeOut(5 * 60 * 1000);
        mOption.setEnableSimulateGps(false);
        mOption.setIsNeedAddress(true);
        mLocationClient.setLocOption(mOption);
        // 注册一个监听函数
        mLocationClient.registerLocationListener(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                UserCurrentAdd.setText(bdLocation.getAddrStr());
                userCurrent = new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());
                UserInfoContext.currentLatLng = new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());
                MyThreadPool.doJob(new Runnable() {
                    @Override
                    public void run() {
                        String longitude = String.valueOf(UserInfoContext.currentLatLng.longitude);
                        String latitude = String.valueOf(UserInfoContext.currentLatLng.latitude);
                        Map<String,String> param = new HashMap<>();
                        param.put("longitude",longitude);
                        param.put("latitude",latitude);
                        HomeFragment.stores = (List<Store>) MyPost.doPost("getMissedStore",param);
                        Message msg = new Message();
                        msg.what = 2;
                        HomeFragment.handler.sendMessage(msg);
                    }
                });
                mLocationClient.stop();
            }
        });
        mLocationClient.start();
    }


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        if(view == null){
            System.out.println("再次执行 onCreateView?");
            System.out.println("flag ==="+flag);
            // 填充 ViewModel中的数据？
            // 进行一次定位操作
             view = inflater.inflate(R.layout.fragment_home, null, false);
             // 定位的操作应该写在这里的
            UserCurrentAdd = view.findViewById(R.id.UserCurrentAddr);
            MainActivity.getMainActivity().UserCurrentAdd = UserCurrentAdd;
            initPosition();
        }
        setHasOptionsMenu(true);
        mLetterAdapter = new LetterAdapter(stores);
        RecyclerView letterReView = view.findViewById(R.id.testRecyclerView);
        letterReView.setAdapter(mLetterAdapter);
        letterReView.setLayoutManager(new GridLayoutManager(getContext(),1));
        //letterReView.setLayoutManager(new LinearLayoutManager(getContext(),RecyclerView.VERTICAL,false));
        UserCurrentAdd = view.findViewById(R.id.UserCurrentAddr);
        updateUserAddr = view.findViewById(R.id.UserUpdateAddr);

        return view;
    }



    private View.OnClickListener listener =  new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            homeFragmentEvent.onImageClickListener(v);
        }
    };

    // 跳转Activity 然后返回的
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    // 对于 Fragment中的组件，要在该方法中进行监听
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        homeFragmentEvent = (FragmentEvent) getActivity();
        updateUserAddr.setOnClickListener(AddrListener);
        UserCurrentAdd.setOnClickListener(AddrListener);

    }

    View.OnClickListener AddrListener = new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            // 跳转到 mapActivity
            Intent intent = new Intent();
            intent.putExtra("fromActivity","MainActivity");
            intent.setComponent(new ComponentName(MainActivity.getMainActivity(), ZdpMapView.class));
            MainActivity.getMainActivity().startActivityForResult(intent,0);
        }
    };



    private class VH extends RecyclerView.ViewHolder{
        // 列表中的每一项
        private ImageView storeImage;
        private TextView storeName;
        public VH(View itemView){
            super(itemView);
            storeImage = itemView.findViewById(R.id.storeImage);
            storeName = itemView.findViewById(R.id.storeName);
        }
    }

    private class LetterAdapter extends  RecyclerView.Adapter<VH>{

        private List<Store> stores;

        public LetterAdapter(List<Store> stores){
            this.stores = stores;
        }

        public void updateAll(List<Store> stores){
            this.stores = stores;
            notifyDataSetChanged();
        }

        // 返回 VH对象。
        // 什么是VH 对象，VH对象和我们列表中显示的项息息相关。
        @NonNull
        @Override
        public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            // 利用 LayoutInflater 创建一个 View
            // 这个 view 的资源文件就是我们刚才创建的那个 xml 文件 (最外层布局）
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_letter,parent,false);
            VH holder = new VH(view);

            // 监听事件 进入店铺详细页
            holder.storeImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = holder.getAdapterPosition(); // 获取当前点击的商家的信息
                    Store store = stores.get(position);
                    // 获取到信息后，打开该商家的Fragment
                    Log.e("监听事件",store.toString());
                    Runnable job = new Runnable() {
                        @Override
                        public void run() {
                            // 执行网络查询
                            Message msg = new Message();
                            ArrayList<FoodType> foodsTypes = (ArrayList<FoodType>) MyPost.doPost("loadStoreHome",store.getId());
                            ArrayList<Food> foods = (ArrayList<Food>) MyPost.doPost("getFoods",store.getId());
                            if(foods == null || foodsTypes == null || foods.size() == 0 || foodsTypes.size() == 0){
                                msg.what = 3;
                                // 店铺内无菜品
                            }else{
                                // 发送消息 ,可以传递bundler 对象。 setData()
                                Bundle b = new Bundle();
                                b.putSerializable("Store",store);
                                b.putSerializable("FoodTypes",foodsTypes);
                                b.putSerializable("Foods",foods);
                                msg.what  =1;
                                msg.setData(b);
                            }
                            handler.sendMessage(msg);
                        }
                    };
                    MyThreadPool.doJob(job);
                }
            });

            return holder;
        }

        // 将数据交给对应的VH来显示 , 数据是在创建适配器的时候传入的。
        // 你要显示什么什么数据， 在这个方法中处理。
        // 一个VH 就是一项数据
        @Override
        public void onBindViewHolder(@NonNull VH holder, int position) {
            // 设置列表中每一项的数据显示
            Store store = stores.get(position);
            // 解析图片 利用 glide 包
            Glide.with(HomeFragment.this).load(store.getStoreImage()).into(holder.storeImage);
            holder.storeImage.setLayoutParams(new RelativeLayout.LayoutParams(500, 400));
            // 填充文字
            holder.storeName.setText(store.getStoreName());

        }

        @Override
        public int getItemCount() {
            if(stores == null){
                return 0;
            }else
                return stores.size();
           // return 0;
        }
    }


}